package com.water.wfo.component.spring.util;

import com.alibaba.fastjson.JSONObject;
import com.water.wfo.component.constant.GlobalConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.IOException;

/**
 * 调用Spring MVC实现的Rest式接口。
 *
 * 
 */
@Slf4j
public final class RestClientUtil {

	/**
	 * post请求
	 * @param url
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static String doPost(String url, Object request) throws IOException {

		String result = null;

		PostMethod postMethod = null;
		Long startTime = System.currentTimeMillis();
		try {
			HttpClient httpClient = new HttpClient();
			postMethod = new PostMethod(url);
			Object object = JSONObject.toJSON(request);
			String json = object.toString();
			RequestEntity requestEntity = new StringRequestEntity(json,
					GlobalConstant.CONTENT_TYPE_JSON, GlobalConstant.ENCODING_UTF8);
			postMethod.setRequestEntity(requestEntity);
			postMethod.addRequestHeader(GlobalConstant.HEADER_CONTENT_TYPE, GlobalConstant.CONTENT_TYPE_JSON_UTF8);
			httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(GlobalConstant.HTTP_CONNECT_TIMEOUT_DEFAULT);
			httpClient.getHttpConnectionManager().getParams().setSoTimeout(GlobalConstant.HTTP_SO_TIMEOUT_DEFAULT);
			int requestCode = httpClient.executeMethod(postMethod);
			if (requestCode == GlobalConstant.HTTP_RESPONSE_SUCCESS) {
				result = postMethod.getResponseBodyAsString();
				log.info("{}调用成功，耗时：{}，请求消息：{}，响应消息：{}", url, System.currentTimeMillis() - startTime,
						json, result);
			}
		} catch (IOException e) {
			log.info("{}调用异常，耗时：{}", url, System.currentTimeMillis() - startTime, e);

			throw e;
		} finally{
			if (postMethod != null) {
				postMethod.releaseConnection();
			}
		}
		/*返回结果对象*/
		return result;
	}
}
